package pre.bookcloud.java21.menu1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

/**
 * Student Attendance System - Main GUI Application
 * Based on the provided prototype interface
 */
public class StudentAttendanceSystem extends JFrame {
    
    /**
     * Custom JButton with rounded corners and gray border
     */
    private static class RoundedButton extends JButton {
        private final int cornerRadius;
        
        public RoundedButton(String text, int cornerRadius) {
            super(text);
            this.cornerRadius = cornerRadius;
            setContentAreaFilled(false);
            setFocusPainted(false);
            setBorderPainted(false);
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            // Draw button background with rounded corners
            g2.setColor(getBackground());
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), cornerRadius, cornerRadius);
            
            // Draw gray border
            g2.setColor(new Color(128, 128, 128));
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawRoundRect(1, 1, getWidth() - 3, getHeight() - 3, cornerRadius, cornerRadius);
            
            g2.dispose();
            super.paintComponent(g);
        }
        
        @Override
        protected void paintBorder(Graphics g) {
            // Border is painted in paintComponent, so we don't need this
        }
    }
    
    private static final String DATA_FILE = "attendance_data.json";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
    
    // UI Components
    private JLabel dateLabel;
    private JPanel studentGridPanel;
    private JButton todayAttendanceBtn;
    private JButton historyAttendanceBtn;
    private JButton statisticsBtn;
    
    // Data
    private Map<String, Student> students;
    
    // Student names from the prototype (6 columns x 4 rows = 24 students)
    private final String[] STUDENT_NAMES = {
        "张子牧", "邢田欣", "赵雅楠", "徐朝高", "徐诗尧", "汪丁扬",
        "蒋外扬", "包浩鸣", "陈慕岩", "张子益", "谢祥辰", "王泽涵", 
        "卜同宇", "李泽宁", "檀奕宁", "薛智予", "曹羽墨", "万钧壮",
        "戴炜博", "马云恒", "徐晨菲", "徐国恩", "朱祥华", "朱蒿岑"
    };
    
    public StudentAttendanceSystem() {
        initializeData();
        initializeUI();
        loadAttendanceData();
    }
    
    private void initializeData() {
        students = new HashMap<>();
        
        // Initialize students with names and auto-generated student numbers
        for (int i = 0; i < STUDENT_NAMES.length; i++) {
            String stuNo = String.format("STU%03d", i + 1);
            Student student = new Student(STUDENT_NAMES[i], stuNo);
            students.put(STUDENT_NAMES[i], student);
        }
    }
    
    private void initializeUI() {
        setTitle("学习签到系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(920, 600);
        setLocationRelativeTo(null);
        setResizable(false);
        
        // Set background color similar to prototype
        getContentPane().setBackground(new Color(240, 240, 240));
        
        // Main layout
        setLayout(new BorderLayout());
        
        // Top panel with navigation buttons
        JPanel topPanel = createTopPanel();
        add(topPanel, BorderLayout.NORTH);
        
        // Center panel with date and student grid
        JPanel centerPanel = createCenterPanel();
        add(centerPanel, BorderLayout.CENTER);
        
        // Update date display
        updateDateDisplay();
    }
    
    private JPanel createTopPanel() {
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        topPanel.setBackground(new Color(240, 240, 240));
        
        // Navigation buttons
        todayAttendanceBtn = createStyledButton("今日签到", new Color(200, 220, 255));
        historyAttendanceBtn = createStyledButton("查看历史签到", new Color(255, 220, 200));
        statisticsBtn = createStyledButton("统计", new Color(220, 255, 200));
        
        // Add action listeners
        todayAttendanceBtn.addActionListener(e -> showTodayAttendance());
        historyAttendanceBtn.addActionListener(e -> showHistoryAttendance());
        statisticsBtn.addActionListener(e -> showStatistics());
        
        topPanel.add(todayAttendanceBtn);
        topPanel.add(historyAttendanceBtn);
        topPanel.add(statisticsBtn);
        
        return topPanel;
    }
    
    private JPanel createCenterPanel() {
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setBackground(new Color(240, 240, 240));
        
        // Date label
        dateLabel = new JLabel();
        dateLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        dateLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dateLabel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
        centerPanel.add(dateLabel, BorderLayout.NORTH);
        
        // Student grid panel
        studentGridPanel = createStudentGridPanel();
        JScrollPane scrollPane = new JScrollPane(studentGridPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 20));
        scrollPane.setBackground(new Color(240, 240, 240));
        centerPanel.add(scrollPane, BorderLayout.CENTER);
        
        return centerPanel;
    }
    
    private JPanel createStudentGridPanel() {
        JPanel gridPanel = new JPanel(new GridLayout(4, 6, 10, 10));
        gridPanel.setBackground(new Color(240, 240, 240));
        gridPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // Create student buttons
        for (String studentName : STUDENT_NAMES) {
            JButton studentBtn = createStudentButton(studentName);
            gridPanel.add(studentBtn);
        }
        
        return gridPanel;
    }
    
    private JButton createStudentButton(String studentName) {
        RoundedButton button = new RoundedButton(studentName, 12); // 12px corner radius
        button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        button.setPreferredSize(new Dimension(120, 45));
        
        // Set initial appearance based on attendance status
        updateButtonAppearance(button, studentName);
        
        // Add click listener
        button.addActionListener(new StudentButtonListener(studentName));
        
        return button;
    }
    
    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setBackground(backgroundColor);
        button.setPreferredSize(new Dimension(100, 30));
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createRaisedBevelBorder());
        return button;
    }
    
    private void updateButtonAppearance(JButton button, String studentName) {
        Student student = students.get(studentName);
        if (student != null && student.isSignedIn()) {
            button.setBackground(new Color(144, 238, 144)); // Light green for signed in
            button.setText(studentName + " ✓");
        } else {
            button.setBackground(Color.WHITE); // White for not signed in
            button.setText(studentName);
        }
    }
    
    private void updateDateDisplay() {
        String today = LocalDate.now().format(DATE_FORMATTER) + "签到";
        dateLabel.setText(today);
    }
    
    private void refreshStudentGrid() {
        Component[] components = studentGridPanel.getComponents();
        for (Component comp : components) {
            if (comp instanceof JButton) {
                JButton button = (JButton) comp;
                String buttonText = button.getText().replace(" ✓", "");
                updateButtonAppearance(button, buttonText);
            }
        }
        studentGridPanel.repaint();
    }
    
    private void showTodayAttendance() {
        // Highlight today attendance button
        todayAttendanceBtn.setBackground(new Color(100, 150, 255));
        historyAttendanceBtn.setBackground(new Color(255, 220, 200));
        statisticsBtn.setBackground(new Color(220, 255, 200));
        
        updateDateDisplay();
        refreshStudentGrid();
    }
    
    private void showHistoryAttendance() {
        // Highlight history attendance button
        historyAttendanceBtn.setBackground(new Color(255, 150, 100));
        todayAttendanceBtn.setBackground(new Color(200, 220, 255));
        statisticsBtn.setBackground(new Color(220, 255, 200));
        
        // Show history dialog
        StringBuilder history = new StringBuilder();
        history.append("历史签到记录:\n\n");
        
        for (Student student : students.values()) {
            if (student.getSignDate() != null) {
                history.append(String.format("%s (%s) - %s - %s\n", 
                    student.getName(), 
                    student.getStuNo(),
                    student.getSignStatus(),
                    student.getSignDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))));
            }
        }
        
        JTextArea textArea = new JTextArea(history.toString());
        textArea.setEditable(false);
        textArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(400, 300));
        
        JOptionPane.showMessageDialog(this, scrollPane, "历史签到记录", JOptionPane.INFORMATION_MESSAGE);
    }
    
    private void showStatistics() {
        // Highlight statistics button
        statisticsBtn.setBackground(new Color(150, 255, 150));
        todayAttendanceBtn.setBackground(new Color(200, 220, 255));
        historyAttendanceBtn.setBackground(new Color(255, 220, 200));
        
        // Calculate statistics
        long signedInCount = students.values().stream()
            .mapToLong(student -> student.isSignedIn() ? 1 : 0)
            .sum();
        long totalStudents = students.size();
        double attendanceRate = totalStudents > 0 ? (double) signedInCount / totalStudents * 100 : 0;
        
        String statistics = String.format(
            "签到统计:\n\n" +
            "总学生数: %d\n" +
            "已签到: %d\n" +
            "未签到: %d\n" +
            "签到率: %.1f%%",
            totalStudents, signedInCount, totalStudents - signedInCount, attendanceRate
        );
        
        JOptionPane.showMessageDialog(this, statistics, "签到统计", JOptionPane.INFORMATION_MESSAGE);
    }
    
    private void saveAttendanceData() {
        try (PrintWriter writer = new PrintWriter(new FileWriter(DATA_FILE))) {
            writer.println("[");
            List<Student> studentList = new ArrayList<>(students.values());
            for (int i = 0; i < studentList.size(); i++) {
                Student student = studentList.get(i);
                writer.print("  " + student.toJson());
                if (i < studentList.size() - 1) {
                    writer.println(",");
                } else {
                    writer.println();
                }
            }
            writer.println("]");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "保存数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void loadAttendanceData() {
        File dataFile = new File(DATA_FILE);
        if (dataFile.exists()) {
            try {
                List<String> lines = Files.readAllLines(Paths.get(DATA_FILE));
                // Simple parsing - look for student data in the JSON
                for (String line : lines) {
                    line = line.trim();
                    if (line.startsWith("{") && line.contains("name")) {
                        parseAndUpdateStudent(line);
                    }
                }
                refreshStudentGrid();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void parseAndUpdateStudent(String jsonLine) {
        try {
            // Simple JSON parsing for our specific format
            String name = extractJsonValue(jsonLine, "name");
            String stuNo = extractJsonValue(jsonLine, "stu_no");
            String signStatus = extractJsonValue(jsonLine, "sign_status");
            String signDate = extractJsonValue(jsonLine, "sign_date");
            String genDate = extractJsonValue(jsonLine, "gen_date");
            
            if (name != null && students.containsKey(name)) {
                Student updatedStudent = Student.fromJsonData(name, stuNo, signStatus, signDate, genDate);
                students.put(name, updatedStudent);
            }
        } catch (Exception e) {
            // Ignore parsing errors for individual entries
        }
    }
    
    private String extractJsonValue(String json, String key) {
        String searchKey = "\"" + key + "\":\"";
        int startIndex = json.indexOf(searchKey);
        if (startIndex == -1) return null;
        
        startIndex += searchKey.length();
        int endIndex = json.indexOf("\"", startIndex);
        if (endIndex == -1) return null;
        
        return json.substring(startIndex, endIndex);
    }
    
    // Inner class for handling student button clicks
    private class StudentButtonListener implements ActionListener {
        private final String studentName;
        
        public StudentButtonListener(String studentName) {
            this.studentName = studentName;
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            Student student = students.get(studentName);
            if (student != null) {
                // If student is currently signed in, show confirmation dialog before canceling
                if (student.isSignedIn()) {
                    int result = JOptionPane.showConfirmDialog(
                        StudentAttendanceSystem.this,
                        "确定要取消 " + studentName + " 的签到吗？",
                        "确认取消签到",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE
                    );
                    
                    // Only proceed with cancellation if user clicked "Yes"
                    if (result != JOptionPane.YES_OPTION) {
                        return; // User clicked "No" or closed dialog, don't cancel
                    }
                }
                
                student.toggleSignStatus();
                
                JButton button = (JButton) e.getSource();
                updateButtonAppearance(button, studentName);
                
                // Save data after status change
                saveAttendanceData();
                
                // Show notification
                String message = student.isSignedIn() ? 
                    studentName + " 签到成功!" : 
                    studentName + " 取消签到!";
                
                JOptionPane.showMessageDialog(StudentAttendanceSystem.this, 
                    message, "签到状态", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
    
    public static void main(String[] args) {
        // Create and show the application
        SwingUtilities.invokeLater(() -> {
            new StudentAttendanceSystem().setVisible(true);
        });
    }
}